#!/bin/sh

e2e_test_install() {
  kubectl create namespace "$CLUSTER_NAMESPACE"
  deploy_curl_pod "$CLUSTER_NAMESPACE"

  wait_pods_running "$CLUSTER_NAMESPACE" 1
}

e2e_test() {
  run_test "Namespace endpoint should be available" check_namespace_status

  run_test "Namespace endpoint should return all kubernetes namespaces" check_namespace

  run_test "User with wrong credentials should not be authenticated" test_authentication_api_error
}

check_namespace() {
  local NAMESPACES_IN_RESPONSE
  local NAMESPACES_IN_K8S

  if wait_until check_returned_namespaces
  then
    success "Namespace endpoint returned all namespaces"
    return 0
  else
    fail "Namespace endpoint not return all namespaces. Expected $NAMESPACES_IN_K8S, actual $NAMESPACES_IN_K8S"
  fi
}

check_returned_namespaces() {
  NAMESPACES_IN_RESPONSE="$(run_curl -r "stackgres/namespaces" -n "$CLUSTER_NAMESPACE" \
    | jq -M -S 'sort_by(.)[]' )"

  NAMESPACES_IN_K8S="$(kubectl get ns -o json \
    | jq -M -S '.items[].metadata.name')"

  [ "$NAMESPACES_IN_RESPONSE" = "$NAMESPACES_IN_K8S" ]
}

get_namespace_status() {
  run_curl -r "stackgres/namespaces" -n "$CLUSTER_NAMESPACE" -e "-LI -o /dev/null -w %{http_code}"
}

check_namespace_status() {
  local HTTP_STATUS

  HTTP_STATUS="$(get_namespace_status)"

  if [ "$HTTP_STATUS" = "200" ] || [ "$HTTP_STATUS" = "202" ] || [ "$HTTP_STATUS" = "204" ]
  then
    success "Namespace endpoint is available"
    return 0
  else
    fail "Namespace endpoint is not available"
  fi
}

test_authentication_api_error() {
  local HTTP_STATUS

  HTTP_STATUS="$(run_curl -j "$FAKE_JWT" -r "stackgres/namespaces"  -n "$CLUSTER_NAMESPACE" -e "-LI -o /dev/null -w %{http_code}")"

  check_authentication_error
}

check_authentication_error() {
  if [ "$HTTP_STATUS" = "401" ]
  then
    echo "Request returned expected authentication error"
    return 0
  else
    echo "Request returned unexpected response status $HTTP_STATUS instead of the expected authentication error."
    return 1
  fi
}